const baseUrl = "https://lovemlc.top:8080";
//const baseUrl = "http://192.168.1.24:8088";

/**
 * wx.request的封装
 * 使用方式： httpExt.get("admin/login", {}).then(res => {}).catch(err => {})
 * @param {*} url 请求地址
 * @param {*} method 请求类型
 * @param {*} data 请求参数
 */
const request = (url, method, data) => {
  wx.showLoading({
    title: '加载中',
    mask: true
  })
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      method: method || 'GET',
      data: method === 'GET' ? data : JSON.stringify(data),
      header: {
        'Content-Type': 'application/json; charset=UTF-8',
        'accessToken': wx.getStorageSync("at"),
        'refreshToken': wx.getStorageSync("rt")
      },
      success(res) {
        var at = res.header.accessToken;
        var rt = res.header.refreshToken;
        if(at && rt){
          wx.setStorageSync("at", at);
          wx.setStorageSync("rt", rt);
        }
        resolve(res);
      },
      fail(error) {
        reject(error)
      },
      complete: info => {
        if(info.statusCode === 401){
          wx.reLaunch({
            url: '/pages/index/index'
          });
        }
        wx.hideLoading();
      }
    })
  })
}

const get = (url, data = {}) => {
  return request(url, 'GET', data, {});
}
const post = (url, data = {}) => {
  return request(url, 'POST', data, {});
}
module.exports = {
  get,
  post,
  baseUrl
}